package ynu.edu.elmservlet.service.impl;

import ynu.edu.elmservlet.dao.UserDao;
import ynu.edu.elmservlet.dao.impl.UserDaoImpl;
import ynu.edu.elmservlet.po.User;
import ynu.edu.elmservlet.service.UserService;
import ynu.edu.elmservlet.util.DBUtil;

public class UserServiceImpl implements UserService {
    private UserDao dao = new UserDaoImpl();

    @Override
    public User getUserByIdByPass(String userId, String password) throws Exception {
        try {
            User user = dao.getUserByIdByPass(userId, password);
            if (user != null) {
                System.out.println("User found: " + user.getUserId());
            } else {
                System.out.println("No user found for userId: " + userId);
            }
            return user;
        } catch (Exception e) {
            System.out.println("Error in getUserByIdByPass: " + e.getMessage());
            throw e;
        }
    }

    @Override
    public int getUserById(String userId) throws Exception {
        int result = 0;
        try {
            DBUtil.getConnection();
            result = dao.getUserById(userId);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            DBUtil.close();
        }
        return result;
    }

    @Override
    public int saveUser(User user) throws Exception {
        int result = 0;
        try {
            DBUtil.getConnection();
            result = dao.saveUser(user);
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        } finally {
            DBUtil.close();
        }
        return result;
    }
}